﻿using System;
using System.Collections.Generic;
using System.Text;
using Estimate.Common.DBFieldTypes;
using Estimate.Common.Memcached;

namespace Estimate.Common.Repository
{

    public abstract class BaseRepository
    {
        protected string _connectionString;

        public string ConnectionString
        {
            get
            {
                return _connectionString;
            }
        }

        protected string _tableName = "";

        public string TableName
        {
            get
            {
                return _tableName;
            }
        }

        public BaseRepository(string connectionString,string tableName)
        {
            _connectionString = connectionString;
            _tableName = tableName;            
        }

        /// <summary>
        /// 是否存在表
        /// </summary>
        /// <returns></returns>
        public bool IsTableExist()
        {
            return DBHelper.IsTableExist(_connectionString, TableName);
        }

        public void ClearTable()
        {
            DBHelper.ExecuteSql(_connectionString, string.Format("DELETE FROM [{0}]", _tableName));
        }

        /// <summary>
        /// 获取建表sql
        /// </summary>
        /// <returns></returns>
        public abstract string GetCreateTableSql();        


        /// <summary>
        /// 创建表结构
        /// </summary>
        public void CreateTable()
        {
            if (this.IsTableExist())
                return;
            string sqlcreate = GetCreateTableSql();
            DBHelper.AddTable(_connectionString, TableName, sqlcreate);
            AfterCreateTable();
        }

        /// <summary>
        /// 删除表
        /// </summary>
        public void DropTable()
        {
            string sql = String.Format("DROP TABLE {0}", TableName);
            DBHelper.ExecuteSql(_connectionString, sql);
        }

       

        public virtual void AfterCreateTable()
        {
 
        }

        /// <summary>
        /// 给定 sendpoint 数组，进行排序，并生成数据库中存储的字符串
        /// </summary>
        /// <param name="sendpoints">sendpoint数组</param>
        /// <returns>数据库中存储的字符串</returns>
        public string getSortedSendpointsString(ForeSendpointType[] sendpoints)
        {
            sendpoints = getSortedSendpoints(sendpoints);

            string[] strs = new string[sendpoints.Length];
            for (int i = 0; i < sendpoints.Length; i++)
            {
                strs[i] = sendpoints[i].ToString();
            }
            return string.Join("|", strs);
        }

        /// <summary>
        /// 生成 sendpoint in ('H06','H15')
        /// </summary>
        /// <param name="sendpoints">sendpoints数组</param>
        /// <returns></returns>
        public string makeSendpointsDBIn(ForeSendpointType[] sendpoints)
        {
            string[] strSendpoints = new string[sendpoints.Length];
            for (int i = 0; i < sendpoints.Length; i++)
            {
                strSendpoints[i] = sendpoints[i].ToString();
            }
            string result = string.Format("'{0}'", string.Join("','", strSendpoints));
            return result;
        }

        /// <summary>
        /// 生成 clock in ('H06','H15')
        /// </summary>
        /// <param name="sendpoints">sendpoints数组</param>
        /// <returns></returns>
        public string makeClocksDBIn(ForeClockType[] clocks)
        {
            string[] strClocks = new string[clocks.Length];
            for (int i = 0; i < clocks.Length; i++)
            {
                strClocks[i] = clocks[i].ToString();
            }
            string result = string.Format("'{0}'", string.Join("','", strClocks));
            return result;
        }

        /// <summary>
        /// 生成 span in ('?','?')
        /// </summary>
        /// <param name="sendpoints">span数组</param>
        /// <returns></returns>
        public string makeSpanDBIn(ForeSpanType[] spans)
        {
            string[] strSpans = new string[spans.Length];
            for (int i = 0; i < spans.Length; i++)
            {
                strSpans[i] = spans[i].ToString();
            }
            string result = string.Format("'{0}'", string.Join("','", strSpans));
            return result;
        }

        /// <summary>
        /// 生成 type in ('?','?')
        /// </summary>
        /// <param name="sendpoints">factor数组</param>
        /// <returns></returns>
        public string makeFactorDBIn(ForeFactorType[] types)
        {
            string[] strFactors = new string[types.Length];
            for (int i = 0; i < types.Length; i++)
            {
                strFactors[i] = types[i].ToString();
            }
            string result = string.Format("'{0}'", string.Join("','", strFactors));
            return result;
        }

        /// <summary>
        /// 给定 sendpoint 数组，进行排序
        /// </summary>
        /// <param name="sendpoints">sendpoint数组</param>
        /// <returns>排序后的sendpoint数组</returns>
        public ForeSendpointType[] getSortedSendpoints(ForeSendpointType[] sendpoints)
        {
            for (int i = 0; i < sendpoints.Length; i++)
            {
                for (int j = i + 1; j < sendpoints.Length; j++)
                {
                    if ((int)sendpoints[i] > (int)sendpoints[j])
                    {
                        ForeSendpointType temp = sendpoints[i];
                        sendpoints[i] = sendpoints[j];
                        sendpoints[j] = temp;
                    }
                }
            }
            return sendpoints;
        }

        /// <summary>
        /// 给定 clock 数组，进行排序
        /// </summary>
        /// <param name="clocks">clock数组</param>
        /// <returns>排序后的clock数组</returns>
        public ForeClockType[] getSortedClock(ForeClockType[] clocks)
        {
            for (int i = 0; i < clocks.Length; i++)
            {
                for (int j = i + 1; j < clocks.Length; j++)
                {
                    if ((int)clocks[i] > (int)clocks[j])
                    {
                        ForeClockType temp = clocks[i];
                        clocks[i] = clocks[j];
                        clocks[j] = temp;
                    }
                }
            }

            return clocks;
        }

        /// <summary>
        /// 对站点号进行排序
        /// </summary>
        /// <param name="stations">站点字符串</param>
        /// <returns>排序后的站点字符串</returns>
        public string getSortedStrings(string stations)
        {
            string[] stationArray = stations.Split(new char[] { ',' });
            for (int i = 0; i < stationArray.Length; i++)
            {
                for (int j = i+1; j < stationArray.Length; j++)
                {
                    if ( stationArray[i].CompareTo(stationArray[j]) > 0)
                    {
                        string temp = stationArray[i];
                        stationArray[i] = stationArray[j];
                        stationArray[j] = temp;
                    }
                }
            }
            return string.Join(",", stationArray);
        }


        private MemcachedClient _cacheClient = null;
        public MemcachedClient CacheClient
        {
            get
            {
                if (_cacheClient == null)
                {
                    if (!MemcachedClient.Exists("localhost"))
                    {
                        MemcachedClient.Setup("localhost", new string[] { "127.0.0.1:11211" });
                    }
                    _cacheClient = MemcachedClient.GetInstance("localhost");
                    _cacheClient.SendReceiveTimeout = 5000;
                    _cacheClient.ConnectTimeout = 5000;
                    _cacheClient.MinPoolSize = 1;
                    _cacheClient.MaxPoolSize = 10;
                }
                return _cacheClient;
            }
        }

        public string getValideCacheKey(List<object> ps)
        {
            string key = string.Join(",", ps);
            return key.Replace("/","").Replace(" ","");
        }
    }
}
